package com.example.hw_smart_home.huawei_api.util;

import okhttp3.*;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.net.URLEncoder;

import javax.net.ssl.*;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

public class HttpUtils {

    private final OkHttpClient client;

    public HttpUtils() {
/*        client = new OkHttpClient.Builder()
                .connectTimeout(15, TimeUnit.SECONDS)
                .readTimeout(15, TimeUnit.SECONDS)
                .writeTimeout(15, TimeUnit.SECONDS)
                .build();*/

        client = getUnsafeOkHttpClient(); // 初始化绕过验证的 OkHttpClient
    }

    private OkHttpClient getUnsafeOkHttpClient() {
        try {
            // 创建信任所有证书的 TrustManager
            final TrustManager[] trustAllCerts = new TrustManager[]{
                    new X509TrustManager() {
                        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {}
                        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {}
                        public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[]{}; }
                    }
            };

            // 安装信任管理器
            final SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
            final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();

            // 创建 OkHttpClient，绕过证书验证和主机名验证
            return new OkHttpClient.Builder()
                    .sslSocketFactory(sslSocketFactory, (X509TrustManager) trustAllCerts[0])
                    .hostnameVerifier((hostname, session) -> true)
                    .build();

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    // 通用 POST 请求，返回响应体和响应头
    public ResponseWithHeaders doPostWithHeaders(String url, Map<String, String> headersMap, String jsonBody) throws IOException {
        RequestBody body = RequestBody.create(jsonBody, MediaType.get("application/json"));

        Request.Builder builder = new Request.Builder().url(url).post(body);
        if (headersMap != null) {
            for (Map.Entry<String, String> entry : headersMap.entrySet()) {
                builder.addHeader(entry.getKey(), entry.getValue());
            }
        }

        try (Response response = client.newCall(builder.build()).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("Unexpected code " + response);
            }
            return new ResponseWithHeaders(response.headers(), response.body().string());
        }
    }

    // 可复用的数据结构：返回 headers + body
    public static class ResponseWithHeaders {
        public Headers headers;
        public String body;

        public ResponseWithHeaders(Headers headers, String body) {
            this.headers = headers;
            this.body = body;
        }
    }

    // 发送 GET 请求，带参数和头部
    public String doGetWithHeaders(String url, Map<String, String> headers, Map<String, String> params) throws IOException {
        // 构造查询参数
        if (params != null && !params.isEmpty()) {
            StringBuilder query = new StringBuilder("?");
            for (Map.Entry<String, String> entry : params.entrySet()) {
                query.append(URLEncoder.encode(entry.getKey(), "UTF-8"))
                        .append("=")
                        .append(URLEncoder.encode(entry.getValue(), "UTF-8"))
                        .append("&");
            }
            query.deleteCharAt(query.length() - 1); // 去掉最后的 &
            url += query;
        }

        // 构造请求头
        Request.Builder requestBuilder = new Request.Builder().url(url);
        if (headers != null) {
            for (Map.Entry<String, String> header : headers.entrySet()) {
                requestBuilder.addHeader(header.getKey(), header.getValue());
            }
        }

        Request request = requestBuilder.build();
        try (Response response = client.newCall(request).execute()) {
            if (response.body() != null) {
                return response.body().string();
            } else {
                return "";
            }
        }
    }

    // 发送 POST 请求，带 JSON 参数和头部
    public String doPost(String url, Map<String, String> headers, String jsonBody) throws IOException {
        MediaType JSON = MediaType.parse("application/json; charset=utf-8");
        RequestBody body = RequestBody.create(jsonBody, JSON);

        Request.Builder requestBuilder = new Request.Builder().url(url).post(body);
        if (headers != null) {
            for (Map.Entry<String, String> header : headers.entrySet()) {
                requestBuilder.addHeader(header.getKey(), header.getValue());
            }
        }

        Request request = requestBuilder.build();
        try (Response response = client.newCall(request).execute()) {
            if (response.isSuccessful() && response.body() != null) {
                return response.body().string();
            } else {
                throw new IOException("请求失败: " + response.code() + " " + response.message());
            }
        }
    }

}
